package com.yjymm.edu.config;

import com.yjymm.edu.common.JwtConfigProperties;
import com.yjymm.edu.interceptor.*;
import com.yjymm.edu.mapper.UserMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.*;

import javax.annotation.Resource;

/**
 * @author yjymm
 * @date 2020-12-20 0:02
 */
@Configuration
@ConditionalOnClass(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties(AdminProperties.class)
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private JwtConfigProperties jwtConfigProperties;

    // 拦截器白名单
    public static String [] LOGIN_WHITE_URL = {
            "/user/login",
            "/user/register",
            "/wx_gateway/openId/**",
            "/user/admin/login",
            "/swagger*",
            "/v2/api-docs",
            "/configuration/ui",
            "/swagger-resources/**",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**"};

    @Resource
    private UserMapper userMapper;

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }


    //添加跨域请求
//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**")
//                .allowedHeaders("Access-Control-Allow-Origin")
//                .allowedOrigins("*")
//                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
//                .maxAge(3600)
//                .allowCredentials(true);
//    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 跨域请求
        registry.addInterceptor(new CrosInterceptor()).addPathPatterns("/**");

        registry.addInterceptor(new CharsetInterceptor()).addPathPatterns("/**");

//        // 验证小程序客户端登陆
//        registry.addInterceptor(new WxLoginInterceptor(this.userMapper))
//                .excludePathPatterns(WebMvcConfig.LOGIN_WHITE_URL)
//                .addPathPatterns("/**");
//
//        // 验证管理员登陆
//        registry.addInterceptor(new TokenInterceptor(jwtConfigProperties))
//                .excludePathPatterns(WebMvcConfig.LOGIN_WHITE_URL)
//                .addPathPatterns("/**");
//
//        // 此LoginInterceptor用在最后！！！，用于返回登陆提示
//        registry.addInterceptor(new LoginInterceptor())
//                .excludePathPatterns(WebMvcConfig.LOGIN_WHITE_URL)
//                .addPathPatterns("/**");
    }

}
